<script>
export default {
  name: 'Study4StuDemo6'
}
</script>

<template>
  <h2>Multiple Timers1</h2>
  <div class="note">
    <h3>effectScope, getCurrentScope, onScopeDispose</h3>
    <p>
      1.
      effectScope：创建一个独立的副作用作用域，可以在该作用域内运行副作用（如响应式的数据监听、计算属性等），并能够在需要时统一清理这些副作用。
    </p>
    <p>2. getCurrentScope：获取当前的作用域，通常用于在自定义组合函数中注册副作用。</p>
    <p>
      3.
      onScopeDispose：注册清理函数，在作用域被销毁时自动调用，适合进行资源释放和清理工作。比如清理事件监听器或取消请求等。
    </p>
  </div>

  <hr class="hr-style" />
  <div class="test">
    <button type="button" @click="runtimer1Scope">runtimer1Scope</button>
    <button type="button" @click="runtimer2Scope">runtimer2Scope</button>
    <button type="button" @click="stoptimer1Scope">stoptimer1Scope</button>
    <button type="button" @click="stoptimer2Scope">stoptimer2Scope</button>
  </div>
  <div class="test">
    <div style="font-size: 30px" v-for="(item, index) in rac" :key="index">{{ item }}</div>
  </div>
  <!-- <div class="test">
  <div style="font-size: 30px;" v-for="(item, index) in rac2" :key="index">{{  item  }}</div>
</div> -->
</template>

<script setup>
import { effectScope, onScopeDispose, reactive, ref } from 'vue'

// 创建一个计时器的组合函数
function useTimer() {
  // 使用 effectScope 创建作用域
  const scope = effectScope()
  return scope
}

function srun(scope, step = 1000) {
  const time = ref(0)
  let interval

  scope.run(() => {
    // 开启计时器
    interval = setInterval(() => {
      console.log(time.value)
      time.value++
    }, step)

    // 在作用域销毁时清理定时器
    onScopeDispose(() => {
      clearInterval(interval)
      console.log('Timer stopped and resources cleaned up.')
    })
  })

  return { time }
}

let timer1 = useTimer()
console.log(timer1)

let rac = reactive([])

const runtimer1Scope = () => {
  let { time } = srun(timer1)
  rac.push(time)
}

const stoptimer1Scope = () => {
  timer1.stop()
}

// 创建定时器timer2
let timer2 = useTimer()
console.log(timer2)

// let rac2 = reactive([])

const runtimer2Scope = () => {
  let { time } = srun(timer2)
  rac.push(time)
}

const stoptimer2Scope = () => {
  timer2.stop()
}
</script>

<style scoped>
body {
  padding: 20px;
}
h2 {
  color: red;
}
h3 {
  color: rgb(220, 85, 85);
}
h4 {
  color: skyblue;
}
.hr-style {
  border: 3px solid gold;
  margin: 20px 0;
}
.note {
  margin: 10px;
  padding: 10px;
  border: 3px solid rgb(221, 121, 202);
}
.note p {
  color: rgb(226, 106, 204);
  font-weight: bold;
}
</style>
